//
//  AreaViewController.m
//  PersonalProject
//
//  Created by 卫建 on 15/12/17.
//  Copyright © 2015年 卫建. All rights reserved.
//

#import "AreaViewController.h"

#import "LocationManager.h"
#import "CustomAnnotation.h"
#import <UIKit/UIKit.h>

#import "Combined.h"

//步数于时间的状态关系
typedef enum {
    RunNumStateStop=0,
    RunNumStateStart,
    //    RunNumStateRunning,
    
} RunNumState;

#define TagStopBtn               100
#define TagStartBtn               101
#define TagSaveBtn                 102
#define TagUploadBtn                103


#define TagTimeLab                                             106
#define TagDistanceLab                                       107
#define TagRunNumberLab                                    108
#define TagAverageVelocityLab                            109



@interface AreaViewController ()<MKMapViewDelegate,CLLocationManagerDelegate>

@property (strong, nonatomic) IBOutlet MKMapView *mapView;

@property (strong, nonatomic) IBOutlet UIButton *startButton;
@property (strong, nonatomic) IBOutlet UIButton *stopButton;
@property (strong, nonatomic) IBOutlet UIButton *suspendButton;
@property (strong, nonatomic) IBOutlet UIButton *saveButton;

@property (strong, nonatomic) IBOutlet UILabel *distanceLable;
@property (strong, nonatomic) IBOutlet UILabel *timeLable;
@property (strong, nonatomic) IBOutlet UILabel *runNumberLable;
@property (strong, nonatomic) IBOutlet UILabel *averageVelocityLable;


@property (nonatomic, assign) NSInteger runNumDate;//一个步数变量, 随步数一直变化
@property (nonatomic, assign) NSInteger runNumStart;//一个步数变量, 只有在每次开始记录时候获取一次 当做初始值
@property(nonatomic,assign) NSInteger  totalRunNumber;//用来记录本次运动得总步数


@property(nonatomic,assign)RunNumState  runNumState; //一个状态标志
@property(nonatomic,assign)CLLocationDistance totalDistance; //总路程
@property (strong, nonatomic) NSTimer * mapUpdate; //更新map方法

@property (strong, nonatomic) NSTimer * timer; //步数统计时间
@property (assign, nonatomic) NSInteger timesInt;//步数统计时间



@property (nonatomic, retain) NSMutableArray* points;
@property (nonatomic, retain) MKPolyline* routeLine;
@property (nonatomic, retain) MKPolylineView* routeLineView;

@property (nonatomic, strong) NSMutableArray *locations;//地址坐标数组


@property(nonatomic,strong)NSMutableArray *array;
@property(nonatomic,strong)NSMutableArray *matubleArray;


#warning asdfghjkl
@property (assign, nonatomic) NSInteger runNum;//运动步数


@property(nonatomic,strong)CLLocationManager *locationManager;


@property(nonatomic,assign)CLLocationDistance distance;

@end

@implementation AreaViewController

@synthesize isKey;
@synthesize isValue;
@synthesize locationManager;









- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self buttonState];
    [self labelState];
    
    //显示用户当前位置
    self.mapView.showsUserLocation = YES;
    
    //设置代理
    self.mapView.delegate = self;
    
    //显示缩放比例
    self.mapView.showsScale = YES;
    
    //实现定位回调的block
    [LocationManager sharedLocationManager].updateBlock = ^(CLLocationCoordinate2D coor)
     {
         //把定位好的位置信息传递给mapView
         MKCoordinateRegion region;
         
         //设置位置的中心点
         region.center = coor;
         
         //span也是一个结构体,他决定了中心点周围信息展示的范围
         MKCoordinateSpan span = MKCoordinateSpanMake(0.1, 0.1);
         region.span = span;
         
         //把位置信息传递给span
         [self.mapView setRegion:region animated:YES];
     };
    
    [self configureRoutes];
    

    
    
    
    self.locationManager = [[CLLocationManager alloc] init];//初始化
    self.locationManager.delegate = self;//委托自己
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;//精度设定
    [self.locationManager startUpdatingLocation];//开启位置更新
    
    
    
    self.matubleArray = [[NSMutableArray alloc]init];
    
    
    
    
//    [LocationManager sharedLocationManager].locationManager = [[CLLocationManager alloc]init];
//    [LocationManager sharedLocationManager].locationManager.delegate = self;
//    [LocationManager sharedLocationManager].locationManager.desiredAccuracy = kCLLocationAccuracyBest;
//    [[LocationManager sharedLocationManager].locationManager startUpdatingLocation];
    
}

#pragma mark-----配置路线
- (void)configureRoutes
{
    // 定义最小值最大值点
    MKMapPoint northEastPoint = MKMapPointMake(0.f, 0.f);
    MKMapPoint southWestPoint = MKMapPointMake(0.f, 0.f);
    
    // 创建一个数组的点
    MKMapPoint* pointArray = malloc(sizeof(CLLocationCoordinate2D) * _points.count);
    
    
    for(int idx = 0; idx < _points.count; idx++)
    {
        CLLocation *location = [_points objectAtIndex:idx];
        CLLocationDegrees latitude  = location.coordinate.latitude;
        CLLocationDegrees longitude = location.coordinate.longitude;
        
        // 创建我们的坐标,并将其添加到正确位置的数组
        CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(latitude, longitude);
        MKMapPoint point = MKMapPointForCoordinate(coordinate);
        
        // if it is the first point, just use them, since we have nothing to compare to yet.
        //如果是第一点,只使用他们,因为我们还没有比较
        if (idx == 0) {
            northEastPoint = point;
            southWestPoint = point;
        } else {
            if (point.x > northEastPoint.x)
                northEastPoint.x = point.x;
            if(point.y > northEastPoint.y)
                northEastPoint.y = point.y;
            if (point.x < southWestPoint.x)
                southWestPoint.x = point.x;
            if (point.y < southWestPoint.y)
                southWestPoint.y = point.y;
        }
        
        pointArray[idx] = point;
    }
    
    if (self.routeLine)
    {
        [self.mapView removeOverlay:self.routeLine];
    }
    
    self.routeLine = [MKPolyline polylineWithPoints:pointArray count:_points.count];
    
    // 覆盖添加到地图
    if (nil != self.routeLine)
    {
        [self.mapView addOverlay:self.routeLine];
    }
    
    // 清除点分配的内存
    free(pointArray);
    
}


- (void)mapView:(MKMapView *)mapView didAddOverlayViews:(NSArray *)overlayViews
{
//    NSLog(@"%@ ----- %@", self, NSStringFromSelector(_cmd));
//    NSLog(@"overlayViews: %@", overlayViews);
}

#pragma mark----------地图划线
- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay
{
//    NSLog(@"%@ ----- %@", self, NSStringFromSelector(_cmd));
    
    MKOverlayView* overlayView = nil;
    
    if(overlay == self.routeLine)
    {
        //if we have not yet created an overlay view for this overlay, create it now.
        if (self.routeLineView) {
            [self.routeLineView removeFromSuperview];
        }
        
        self.routeLineView = [[MKPolylineView alloc] initWithPolyline:self.routeLine];
        self.routeLineView.fillColor = [UIColor colorWithRed:0.4177 green:0.5069 blue:1.0 alpha:1.0];
        self.routeLineView.strokeColor = [UIColor colorWithRed:0.1407 green:0.7778 blue:1.0 alpha:1.0];
        self.routeLineView.lineWidth = 10;
        
        
        overlayView = self.routeLineView;
    }
    
    return overlayView;
    
}

#pragma mark------显示区域发生改变后触发
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
//    NSLog(@"%@ ----- %@", self, NSStringFromSelector(_cmd));
    
    CLLocation *location = [[CLLocation alloc] initWithLatitude:userLocation.coordinate.latitude
                                                      longitude:userLocation.coordinate.longitude];
    // check the zero point
    if  (userLocation.coordinate.latitude == 0.0f ||
         userLocation.coordinate.longitude == 0.0f)
        
        return;
    
    // 检查移动的距离
    if (_points.count > 0)
    {
        CLLocationDistance distance = [location distanceFromLocation:(CLLocation *)[LocationManager sharedLocationManager].locationManager];
        if (distance < 5)
            return;
    }
    
    if (nil == _points)
    {
        _points = [[NSMutableArray alloc] init];
    }
    
    [_points addObject:location];
    [LocationManager sharedLocationManager].locationManager = (CLLocationManager *)location;
    
    NSLog(@"points: %@", _points);
    
    [self configureRoutes];
    
    CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(userLocation.coordinate.latitude, userLocation.coordinate.longitude);
    [self.mapView setCenterCoordinate:coordinate animated:YES];
}


#pragma mark-----设置button初始的显示隐藏状态以及tag值
-(void)buttonState
{
    self.stopButton.hidden = NO;
    self.saveButton.hidden = YES;
    self.startButton.hidden = YES;
    self.suspendButton.hidden = YES;
    
    self.stopButton.tag = TagStopBtn;
    self.saveButton.tag = TagSaveBtn;
    self.startButton.tag = TagStartBtn;
    self.suspendButton.tag = TagUploadBtn;
    
    self.stopButton.clipsToBounds = YES;
    self.stopButton.layer.cornerRadius = 25;
    self.startButton.clipsToBounds = YES;
    self.startButton.layer.cornerRadius = 25;
    self.saveButton.clipsToBounds = YES;
    self.saveButton.layer.cornerRadius = 25;
    self.suspendButton.clipsToBounds = YES;
    self.suspendButton.layer.cornerRadius = 25;
    
}

#pragma mark-----设置label的状态
-(void)labelState
{
    self.timeLable.tag = TagTimeLab;
    self.distanceLable.tag = TagDistanceLab;
    self.runNumberLable.tag = TagRunNumberLab;
    self.averageVelocityLable.tag = TagAverageVelocityLab;
}

//#pragma mark-----实现自定义大头针的代理方法
//-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
//{
//    
//    if ([[annotation title]isEqualToString:@"ai"])
//    {
//        //如果是的话
//        MKAnnotationView *view = [mapView dequeueReusableAnnotationViewWithIdentifier:@"flag"];
//        if (view == nil)
//        {
//            view = [[MKAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:@"flag"];
//        }
//        
//        return view;
//    }
//    return nil;
//}
//


#pragma mark-------当页面显示时
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if ([isKey isEqualToString:@"0"])
    {
        [self startMapAndRun];//初始化
    }
    
//    添加开始图标  设置延迟  图标位置 较精确
    [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(startroute) userInfo:nil repeats:NO];
    
    
    //运动了多久,,, 每秒刷新一次
    //    _timesInt = 0;
    _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(refreshData) userInfo:nil repeats:YES];//记录
    
    
    
}

#pragma mark  地图开始,起始点标记
- (void)startroute
{
    
//    [self addAnnotation];
    
    CLLocationDegrees latitude = _mapView.userLocation.coordinate.latitude;
    CLLocationDegrees longitude = _mapView.userLocation.coordinate.longitude;
    
    
    CLLocationCoordinate2D startPt = (CLLocationCoordinate2D){latitude, longitude};
    
    NSLog(@"----------%lf,%lf",latitude,longitude);
    
    [[LocationManager sharedLocationManager]getAddressWithCoordinate:startPt withFinish:^(NSString *address) {
        
        CustomAnnotation *annotation = [[CustomAnnotation alloc]init];
        
//        annotation.title = [LocationManager sharedLocationManager].mark.name;
        annotation.coordinate = startPt;
        
        annotation.title = [[LocationManager sharedLocationManager].dictionary valueForKey:@"Street"];
        
        annotation.subtitle = [[LocationManager sharedLocationManager].dictionary valueForKey:@"State"];
        
        [_mapView addAnnotation:annotation];
        
        
    }];
    

    
}

//#pragma mark 添加大头针
//-(void)addAnnotation
//{
//    CLLocationCoordinate2D location1=CLLocationCoordinate2DMake(39.95, 116.35);
//    CustomAnnotation *annotation1=[[CustomAnnotation alloc]init];
//    annotation1.title=@"CMJ Studio";
//    annotation1.subtitle=@"Kenshin Cui's Studios";
//    annotation1.coordinate=location1;
//    
//    [_mapView addAnnotation:annotation1];
//    
//    CLLocationCoordinate2D location2=CLLocationCoordinate2DMake(39.87, 116.35);
//    CustomAnnotation *annotation2=[[CustomAnnotation alloc]init];
//    annotation2.title=@"Kenshin&Kaoru";
//    annotation2.subtitle=@"Kenshin Cui's Home";
//    annotation2.coordinate=location2;
//    
//    [_mapView addAnnotation:annotation2];
//}



#pragma mark //每秒钟调用一次
-(void)refreshData
{
    _timesInt +=1;
    
    self.distanceLable = (UILabel *)[self.view viewWithTag:TagDistanceLab];
    
    self.averageVelocityLable = (UILabel *)[self.view viewWithTag:TagAverageVelocityLab];
    self.runNumberLable = (UILabel *)[self.view viewWithTag:TagRunNumberLab];
    
    
    NSString *str_hour = [NSString stringWithFormat:@"%02ld",_timesInt/3600];
    NSString *str_minute = [NSString stringWithFormat:@"%02ld",(_timesInt%3600)/60];
    NSString *str_second = [NSString stringWithFormat:@"%02ld",_timesInt%60];
    NSString *format_time = [NSString stringWithFormat:@"%@:%@:%@",str_hour,str_minute,str_second];
    self.timeLable.text = format_time;
    
    
    self.runNumberLable.text = [NSString stringWithFormat:@"%d 步",(int)((int)self.totalDistance * 2.3 - 9)];
    
    if (_totalDistance < 1000) {
        self.distanceLable.text =[NSString stringWithFormat:@"%.2f M",_totalDistance];
    }else{
        self.distanceLable.text =[NSString stringWithFormat:@"%.2f km",_totalDistance / 1000.0];
    }
    
    float averageVelocity = (float)_totalDistance / 1000 / ((float)_timesInt / 3600);
    self.averageVelocityLable.text = [NSString stringWithFormat:@"%.2fKm/h",averageVelocity];
//    self.totalRunNumber = self.runNumDate - self.runNumStart;
//    NSLog(@"########################### runNumdate = %ld",_runNumDate);
//    self.runNumberLable.text =[NSString stringWithFormat:@"%ld",_totalRunNumber];
//    
//    NSLog(@"------------------------------_totalRunNumber = %ld",_totalRunNumber);
    
    
    
    
    
    
    //获取步数广播
    [[NSNotificationCenter defaultCenter]  addObserver:self  selector:@selector(updateRunNum:) name:@"RunNum" object:nil];
    
}



#pragma mark-------初始化位置和时间
-(void)startMapAndRun
{
//    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    
    //地图中心显示当前位置
    _runNumState = RunNumStateStart;
    _totalDistance = 0;//距离初始化 0米
    _runNumDate = 0;//step 0
    _mapUpdate = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(handleTime) userInfo:nil repeats:YES];
    
    [_mapView addObserver:self forKeyPath:@"myLocation" options:NSKeyValueObservingOptionNew context:nil];
    
    
    
    self.runNumberLable.text =[NSString stringWithFormat:@"%d",0]; //步数清零
    
    
    
}


#warning 这里有问题没有解决
#pragma mark-----更新位置信息的方法
- (void)handleTime
{
//    [[LocationManager sharedLocationManager] startLocation];
}

#pragma mark------点击开始按钮响应事件
- (IBAction)startButtonDidClicked:(id)sender
{
    UIButton *senderBtn =(UIButton *)sender;
    [self hidden:senderBtn];
    
    
    _timesInt = 0;//记步时间初始化为0
    _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(refreshData) userInfo:nil repeats:YES];//记录运动了多久,,, 每秒刷新一次
    _mapUpdate = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(handleTime) userInfo:nil repeats:YES];
    
    _runNumDate = 0;
    
    [self configureRoutes];//地图开始重新划线
    
    [self startMapAndRun];
}

#pragma mark------点击停止按钮响应事件
- (IBAction)stopButtonDidClicked:(id)sender
{
    UIButton *senderBtn =(UIButton *)sender;
    [self hidden:senderBtn];
    _runNumState =RunNumStateStop; //状态标记为停止
    _totalDistance = 0;//初始化距离 0 米
    _runNumDate = 0;
    
    [_timer invalidate];
    
    //    添加开始图标  设置延迟  图标位置 较精确
    [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(stopRoute) userInfo:nil repeats:NO];
    
    
//    /-------添加结束位置图标------
//    [[LocationManager sharedLocationManager]stopLocation];
//      [_mapView stopRendering];//停止绘制
    
}

#pragma mark------点击保存按钮响应事件
- (IBAction)saveButtonDidClicked:(id)sender
{
    
}

#pragma mark-----点击上传按钮响应事件
- (IBAction)suspendButtonDidClicked:(id)sender
{
    
}

#pragma mark-------点击停止按钮展示当时的大头针
-(void)stopRoute
{
    CLLocationDegrees latitude = _mapView.userLocation.coordinate.latitude;
    CLLocationDegrees longitude = _mapView.userLocation.coordinate.longitude;
    
    
    CLLocationCoordinate2D stopPt = (CLLocationCoordinate2D){latitude, longitude};
    
    NSLog(@"----------%lf,%lf",latitude,longitude);
    
    [[LocationManager sharedLocationManager]getAddressWithCoordinate:stopPt withFinish:^(NSString *address) {
        
        CustomAnnotation *annotation1 = [[CustomAnnotation alloc]init];
        
        //        annotation.title = [LocationManager sharedLocationManager].mark.name;
        annotation1.coordinate = stopPt;
        
        //允许弹出气泡
//        annotation.canShowCallout = YES;
        
        annotation1.title = [[LocationManager sharedLocationManager].dictionary valueForKey:@"State"];
        
//        annotation.subtitle = [[LocationManager sharedLocationManager].dictionary valueForKey:@"State"];
        
        [_mapView addAnnotation:annotation1];
        
        
    }];
}

#pragma mark  按钮隐藏/显示逻辑
-(void)hidden:(id)sender
{
    self.stopButton = (UIButton *)[self.view viewWithTag:TagStopBtn];
    self.startButton = (UIButton *)[self.view viewWithTag:TagStartBtn];
    self.saveButton = (UIButton *)[self.view viewWithTag:TagSaveBtn];
    self.suspendButton = (UIButton *)[self.view viewWithTag:TagUploadBtn];
    
    UIButton *senderBtn=(UIButton *)sender;
    NSInteger tagInt=[senderBtn tag];
    
    switch (tagInt)
    {
        case TagStopBtn:
            self.stopButton.hidden = YES;
            self.startButton.hidden = NO;
            self.saveButton.hidden = NO;
            self.suspendButton.hidden = NO;
            
            break;
        case TagStartBtn:
            self.stopButton.hidden = NO;
            self.startButton.hidden = YES;
            self.saveButton.hidden = YES;
            self.suspendButton.hidden = YES;
            
            break;
            
        default:
            break;
    }
}





- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{
    
    NSLog(@"oldLocation.coordinate.timestamp:%@", oldLocation.timestamp);
    NSLog(@"oldLocation.coordinate.longitude:%f", oldLocation.coordinate.longitude);
    NSLog(@"oldLocation.coordinate.latitude:%f", oldLocation.coordinate.latitude);
    
    NSLog(@"newLocation.coordinate.timestamp:%@", newLocation.timestamp);
    NSLog(@"newLocation.coordinate.longitude:%f", newLocation.coordinate.longitude);
    NSLog(@"newLocation.coordinate.latitude:%f", newLocation.coordinate.latitude);
    
    
    
//    CLLocationDegrees  latitude = _mapView.centerCoordinate.latitude;
//    CLLocationDegrees longitude = _mapView.centerCoordinate.longitude;
    
    
    //1.将两个经纬度点转成投影点
    MKMapPoint point1 = MKMapPointForCoordinate(CLLocationCoordinate2DMake(oldLocation.coordinate.latitude ,oldLocation.coordinate.longitude));
    MKMapPoint point2 = MKMapPointForCoordinate(CLLocationCoordinate2DMake(newLocation.coordinate.latitude ,newLocation.coordinate.longitude));
    
    
    
    
    //2.计算距离
    self.distance = MKMetersBetweenMapPoints(point1,point2);
    
    
    
//    CLLocationDistance totalDis = self.distance;
    
    
//    self.array = [[NSArray alloc]initWithObjects:[NSString stringWithFormat:@"%f",self.distance], nil];
    
    
    [self.array addObject:[NSString stringWithFormat:@"%f",self.distance]];
    
    NSLog(@"----------1234567---------array=%@",self.array);
    
    
    
    NSLog(@"**********************distance%f",self.distance);
    
    if (self.distance > 10000)
    {
        return;
    }
    
    self.totalDistance += self.distance;
    
    NSLog(@"**************************totalDistance%f",self.totalDistance);
    
    self.distanceLable.text = [NSString stringWithFormat:@"%.2f M",self.totalDistance];
    
    
    
    [self.matubleArray addObject:[NSString stringWithFormat:@"%3.4f;%3.4f",[newLocation coordinate].latitude, [newLocation coordinate].longitude]];
    
    NSLog(@"---------array = %@",self.matubleArray);
    
    
//    NSString *LoStr = [NSString stringWithFormat:@"%3.4f;%3.4f",[newLocation coordinate].latitude, [newLocation coordinate].longitude];
//    
//    
//    NSUserDefaults* Defaults = [NSUserDefaults standardUserDefaults];
//    [Defaults setObject:LoStr forKey:@"LoStr"];
    
    
    
    
    //有步数统计才能触发 保存经纬度
    if (_runNumState == RunNumStateStart)
    {
        [_locations addObjectsFromArray:_matubleArray];
        
        NSLog(@"++++++++++++++++ _location = %@",_locations);
        
        _totalDistance=[Combined calculateTotalDistance:_totalDistance LocationData:_locations];
        
    }
}


#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    switch (error.code)
    {
        case kCLErrorLocationUnknown:
            NSLog(@"The location manager was unable to obtain a location value right now.");
            break;
        case kCLErrorDenied:
            NSLog(@"Access to the location service was denied by the user.");
            break;
        case kCLErrorNetwork:
            NSLog(@"The network was unavailable or a network error occurred.");
            break;
        default:
            NSLog(@"undefine");
            break;
    }
}


#warning asdfghjkl
#pragma mark //随时获取步数记录
-(void)updateRunNum:(NSNotification *)notification
{
    NSString *runNum= [notification object];
    NSInteger runNums=[runNum intValue];
    //runNums = 0;
    NSLog(@"-----------------------------------------------------------------\n\n ------------------------------------------\n");
    _runNumDate=runNums;//随时记录步数变量
    NSLog(@"_runNumDate==%ld",_runNumDate);
    
    if ( _runNumState == RunNumStateStop)//设置一个状态,. 控制是否需要保存当前得值
    {
        _runNumStart = runNums;
        _runNumState = RunNumStateStart;
    }
}


-(NSMutableArray *)array
{
    if (!_array)
    {
        _array = [[NSMutableArray alloc]init];
    }
    return _array;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
